import { useEffect } from 'react';
import { useAppDispatch, useAppSelector } from '../store/hooks';
import { loadUserFromStorage, fetchUserProfile } from '../store/slices/authSlice';

export const useAuth = () => {
  const dispatch = useAppDispatch();
  const { user, token, isAuthenticated, loading, error } = useAppSelector(
    (state: any) => state.auth
  );

  useEffect(() => {
    // 应用启动时从localStorage加载用户信息
    const localToken = localStorage.getItem('token');
    const localUser = localStorage.getItem('user');
    
    if (localToken && localUser && (!user || !token)) {
      dispatch(loadUserFromStorage());
    }
  }, [dispatch, user, token]);

  useEffect(() => {
    // 如果有token但没有用户信息，尝试获取用户信息
    if (token && !user && !loading) {
      dispatch(fetchUserProfile());
    }
  }, [dispatch, token, user, loading]);

  return {
    user,
    token,
    isAuthenticated,
    loading,
    error,
  };
};